package com.bw.service.orders.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.group.OrdergroupEntity;
import com.bw.entity.material.PiMaterial;
import com.bw.entity.orders.*;

import com.bw.entity.pay.PiPayLog;
import com.bw.entity.process.PiProcess;
import com.bw.entity.user.TbUser;
import com.bw.mapper.gy.GyMapper;

import com.bw.mapper.orders.PiOrderItemMapper;

import com.bw.mapper.orders.PiOrderMapper;
import com.bw.req.*;
import com.bw.service.customer.IPiCustomerService;
import com.bw.service.material.IPiMaterialService;
import com.bw.service.orders.IPiOrderItemMaterialService;
import com.bw.service.orders.IPiOrderItemProcessService;
import com.bw.service.orders.IPiOrderLogService;
import com.bw.service.orders.IPiOrderService;
import com.bw.service.pay.IPiPayLogService;
import com.bw.service.process.IPiProcessService;
import com.bw.service.user.ITbUserService;
import com.bw.utils.aliPay.AlipayConfig;
import net.sf.excelutils.ExcelException;
import net.sf.excelutils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-19
 */
@Service
public class PiOrderServiceImpl extends ServiceImpl<PiOrderMapper, PiOrder> implements IPiOrderService {
    @Resource
    private GyMapper gyMapper;

    @Autowired
    private PiOrderMapper orderMapper;
    @Autowired
    private PiOrderItemMapper itemMapper;

    @Autowired
    private IPiOrderService orderService;

    @Autowired
    private IPiCustomerService customerService;

    @Autowired
    private ITbUserService userService;
    @Autowired
    private IPiOrderItemMaterialService orderItemMaterialService;
    @Autowired
    private IPiMaterialService materialService;

    @Autowired
    private IPiOrderItemProcessService orderItemProcessService;

    @Autowired
    private IPiProcessService processService;

    @Autowired
    private IPiPayLogService payLogService;
    @Autowired
    private IPiOrderLogService orderLogService;

    @Override
    public List<GyVO> findGy(PiOrder piOrder) {
        return gyMapper.findGy(piOrder);
    }

    @Transactional
    @Override
    public void insertGoup(OrdergroupEntity entity) {
        BigDecimal price = new BigDecimal("0");
        if (entity.getPiOrder().getId() == null) {
            orderMapper.insertOrder(entity.getPiOrder());
        } else {
            orderMapper.updateById(entity.getPiOrder());
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("orderId", entity.getPiOrder().getId());
        itemMapper.delete(queryWrapper);
        List<PiOrderItem> items = entity.getPiOrderItems();
        for (PiOrderItem i : items) {
            price=price.add(i.getPrice());
            i.setOrderId(entity.getPiOrder().getId());
            itemMapper.insert(i);
        }
        entity.getPiOrder().setPrice(price);
        entity.getPiOrder().setPriceIt(price.multiply(entity.getPiOrder().getTaxRate()));
        orderMapper.updateById(entity.getPiOrder());

    }

    @Override
    public void getBao(long id, HttpServletResponse response) throws IOException, ExcelException {
        PiOrder order=orderService.getById(id);//查询订单信息
        PiCustomer piCustomer =customerService.getById(order.getCustomerId());//查询客户信息
        TbUser user = userService.getById(order.getTbId());//用户信息

        //总价
        BigDecimal priceIt = new BigDecimal(0);
        BigDecimal taxrates=new BigDecimal(0);

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("orderId",id);
        List<PiOrderItem> orderItemList = itemMapper.selectList(queryWrapper);

        List<Map> mapList=new ArrayList<>();
        int i=1;
        for(PiOrderItem piOrderItem:orderItemList){


            //零件单价
            BigDecimal productprice = new BigDecimal(0);


            Map map =new HashMap<>();
            map.put("no",+i++);
            map.put("code",piOrderItem.getCode());//零件编号
            map.put("name",piOrderItem.getName());//零件名称
            map.put("total",piOrderItem.getNum());//加工数量

            QueryWrapper queryWrapper1=new QueryWrapper();
            queryWrapper1.eq("orderItemId", piOrderItem.getId());
            List<PiOrderItemMaterial> orderItemMaterialList = orderItemMaterialService.list(queryWrapper1);

            String materialname="";
            BigDecimal materialcost=new BigDecimal(0);
            for(PiOrderItemMaterial piOrderItemMaterial:orderItemMaterialList){
                PiMaterial piMaterial = materialService.getById(piOrderItemMaterial.getMaterialId());
                materialname=materialname+piMaterial.getName()+",";
                materialcost=materialcost.add(piOrderItemMaterial.getMaterCost());
            }
            materialcost=materialcost.multiply(new BigDecimal(piOrderItem.getNum()));

            productprice=productprice.add(materialcost);//零件中加上材料费

            map.put("materialname",materialname);//材料
            map.put("materialcost",materialcost);//材料费

            QueryWrapper queryWrapper5=new QueryWrapper();
            queryWrapper5.eq("orderItemId",piOrderItem.getId());
            List<PiOrderItemProcess> piOrderItemProcesses = orderItemProcessService.list(queryWrapper5);
            String bcnames="";
            BigDecimal workhour=new BigDecimal(0);
            BigDecimal workcost=new BigDecimal(0);
            BigDecimal heatcost=new BigDecimal(0);
            BigDecimal surfacecost=new BigDecimal(0);
            for(PiOrderItemProcess piOrderItemProcess:piOrderItemProcesses){
                PiProcess piProcess = processService.getById(piOrderItemProcess.getProcessId());
                if(piProcess.getCType()==0){//按时间计算
                    workcost=workcost.add(piOrderItemProcess.getProCost());
                }
                if(piProcess.getCType()==1){//按重量
                    heatcost=heatcost.add(piOrderItemProcess.getProCost());
                }
                if(piProcess.getCType()==1){//按面积
                    bcnames=bcnames+piProcess.getName()+",";
                    surfacecost=surfacecost.add(piOrderItemProcess.getProCost());
                }
                workhour=workhour.add(new BigDecimal(piOrderItemProcess.getSgWorkHour()));
            }
            workhour=workhour.multiply(new BigDecimal(piOrderItem.getNum()));
            workcost=workcost.multiply(new BigDecimal(piOrderItem.getNum()));
            heatcost=heatcost.multiply(new BigDecimal(piOrderItem.getNum()));
            surfacecost=surfacecost.multiply(new BigDecimal(piOrderItem.getNum()));

            map.put("bcnames",bcnames);//表面处理
            map.put("workhour",workhour);//零件工时
            map.put("workcost",workcost);//零件加工费
            map.put("heatcost",heatcost);//零件热处理费
            map.put("surfacecost",surfacecost);//零件表面处理费
            //含税单价
            //BigDecimal taxRate = new BigDecimal(order.getTaxRate()+1).setScale(2,BigDecimal.ROUND_HALF_UP);//税率
            BigDecimal taxrate=new BigDecimal("1");
            taxrate=taxrate.subtract(order.getTaxRate());
            taxrates=taxrate;

            productprice=productprice.add(workcost);
            productprice=productprice.add(heatcost);
            productprice=productprice.add(surfacecost);
            productprice=productprice.multiply(taxrate).setScale(4,BigDecimal.ROUND_HALF_UP);
           // res.setProductprice(productprice);
            map.put("productprice",productprice);
            //总价
            BigDecimal num = new BigDecimal(piOrderItem.getNum());
            BigDecimal totalprice = new BigDecimal(0);
            totalprice=productprice.multiply(num);
            //res.setTotalprice(totalprice);
            map.put("totalprice",totalprice);

            priceIt=priceIt.add(totalprice);
            //总价
            map.put("priceIt",totalprice);

//            BigDecimal taxrate=new BigDecimal("100");
//            taxrate=taxrate.add(order.getTaxRate());
//            taxrate=taxrate.divide(new BigDecimal("100"),2, RoundingMode.HALF_UP);
//            map.put("productprice",piOrderItem.getPrice().multiply(taxrate));
//            map.put("totalprice",piOrderItem.getPrice().multiply(taxrate).multiply(new BigDecimal(piOrderItem.getNum())));
            mapList.add(map);
        }
        order.setPriceIt(priceIt);//2, BigDecimal.ROUND_HALF_UP
        order.setPrice(priceIt.divide(taxrates,2, BigDecimal.ROUND_HALF_UP));
        orderService.saveOrUpdate(order);

        ClassPathResource classPathResource=new ClassPathResource("xls/Quotation.xls");
       // ClassPathResource classPathResource=new ClassPathResource("xls/Quotation.xls");
        InputStream inputStream = classPathResource.getInputStream();
        ExcelUtils.addValue("orderItemList",mapList);
        ExcelUtils.addValue("customer",piCustomer);
        ExcelUtils.addValue("user",user);
        ExcelUtils.addValue("order",order);
        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());
    }

    @Override
    public List<CusOrder> cusList() {
        return orderMapper.cusList();
    }

    @Override
    public List<CusOrder1> gyList() {
        return orderMapper.gyList();
    }

    @Override
    public List<CusOrder3> xsList() {
        return orderMapper.xsList();
    }

    @Override
    public List<CusOrder2> ordersList() {
        return orderMapper.ordersList();
    }

    @Override
    public void orderTask() throws AlipayApiException, UnsupportedEncodingException {
        HttpServletRequest request=null;
        //查询状态为未支付
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state",3);
        queryWrapper.or();
        queryWrapper.eq("state",4);
        List<PiOrder> list = orderMapper.selectList(queryWrapper);
        for(PiOrder o: list){
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();


            //请二选一设置

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ o.getCode()+"\"}");

            //请求
            String result = alipayClient.execute(alipayRequest).getBody();
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            //验证码签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params,AlipayConfig.alipay_public_key,AlipayConfig.charset, AlipayConfig.sign_type);
            if(signVerified){
                o.setState(5);
                //userId,支付类型，支付状态
                orderMapper.updateById(o);
                //支付日志
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("out_trade_no",o.getCode());
                PiPayLog payLog = payLogService.getOne(queryWrapper1);
                payLog.setId(null);
                payLog.setCreateTime(new Date());
                payLog.setTradeNo(alipayClient.execute(alipayRequest).getTradeNo());
                payLog.setTradeNo("1");
                payLogService.saveOrUpdate(payLog);
                //订单日志
                PiOrderLog piOrderLog = new PiOrderLog();
                QueryWrapper queryWrapper2 = new QueryWrapper();
                queryWrapper.eq("ID",o.getUpdateUser());
                TbUser user = userService.getOne(queryWrapper2);
                piOrderLog.setOrderId(o.getId());
                piOrderLog.setRemarks("订单付款成功");
                piOrderLog.setUserName(user.getFullName());
                piOrderLog.setTbId(user.getId());
                orderLogService.saveOrUpdate(piOrderLog);


            }else{
                System.out.println("验签失败");
            }
            long time = o.getUpdateDate().getTime();
            long time1 = new Date().getTime();
           long l= (time1-time1)/(60*1000);
           if(l>30){
               o.setState(6);
               o.setUpdateDate(new Date());
               orderService.saveOrUpdate(o);
           }

        }
    }


}
